const gulp = require('gulp');
const foal = require('gulp-foal')();
const clean = require('gulp-clean');
const sourcemaps = require('gulp-sourcemaps');
const babel = require('gulp-babel');
const webpack = require('webpack-stream');
const named = require('vinyl-named');
const plumber = require('gulp-plumber');
const sequence = require('gulp-sequence');

const path = require('path');
const colors = require('colors/safe');

const src = 'src';
const clientDest = 'public/dist';
const serverDest = 'dist';
const serverEntries = [src + "/" + "server/**/*.js", src + "/" + "server/**/*.jsx", src + "/" + 'server/bin/*'];
const clientEntries = [src + "/" + "client/**/*.js", src + "/" + "client/**/*.jsx"];
const shareEntries = [src + "/" + "share/**/*.js", src + "/" + "share/**/*.jsx"];

foal.task('babel', function (fp) {
    let filePath = fp || [].concat(serverEntries, shareEntries);
    return gulp
        .src(filePath, {
            base: src
        })
        .pipe(plumber())
        .pipe(sourcemaps.init())
        .pipe(babel({
            filenameRelative: './.babelrc'
        }))
        .pipe(sourcemaps.write('.', {
            sourceRoot: '../' + src
        }))
        .pipe(gulp.dest(serverDest));
});

foal.task('clean', function (fp) {
    let filePath = fp || [clientDest, serverDest];
    return gulp.src(filePath, {
        base: src,
    }).pipe(clean());
});


gulp.task('clean', cb => foal.run(foal.clean(), cb));

gulp.task('webpack', function() {
    var config = require('./webpack.config.js');
    return gulp
        .src([].concat(clientEntries, shareEntries), {
            base: src
        })
        .pipe(plumber())
        .pipe(named())
        .pipe(webpack(config))
        .pipe(gulp.dest(clientDest));

});

gulp.task('babel', cb => foal.run(foal.babel(), cb));

gulp.task('build', sequence('clean', 'babel'));

gulp.task('default', function () {
    // var config = require('./webpack.config.js');
    // config['watch'] = true;
    gulp.start('build');
    gulp.watch([serverEntries, shareEntries])
        .on('change', function (event) {
            let srcFileName = event.path.replace(path.join(__dirname, "/"), "");
            switch (event.type) {
                case 'changed':
                case 'added':
                    let filesName = event.path.replace(path.join(__dirname, src), "").replace(/x$/, "");
                    let files = [path.join(serverDest, filesName), path.join(serverDest, filesName + ".map")]
                    foal.run(foal.babel(event.path), function () {
                        console.log(colors.green(srcFileName + ' -> ' + files));
                    });
                    break;
                case 'deleted':
                    console.log(colors.green(srcFileName + ' -> ' + Null));
                    foal.run(foal.clean(files));
                    break;
            }
        });
});